from flask import render_template
from werkzeug.security import generate_password_hash #hash加密
import random
from datetime import datetime
from appdir import app, db
from appdir.models import User, Resource, News

from dateutil import parser
from shutil import copyfile
import numpy as np
import xlrd3


#删除目录内所有文件
import os
def delfile(path):
    for i in os.listdir(path) : # 返回当前目录下面的所有文件相对路径
        file = path + "/" + i #生成绝对路径
        if os.path.isfile(file) == True: #判断是否为文件
            os.remove(file)


@app.route('/test')
def test():
    # # 删除
    # db.drop_all()
    # db.create_all()

    # path = 'appdir/static/file'
    # delfile(path)
    # path = 'appdir/static/image'
    # delfile(path)


    with open("test/wisdom.txt") as file:
        wisdom = file.readlines()
    file.close()

    # 用于产生姓，源自网络    
    first_name  = ["赵", "钱", "孙", "李", "周", "吴", "郑", 
        "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", 
        "朱", "秦", "尤", "许", "何", "吕", "施", "张", "孔", 
        "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", 
        "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", 
        "葛", "奚", "范", "彭", "郎", "鲁", "韦", "昌", "马", 
        "苗", "凤", "花", "方"]
    # 用于产生名，源自网络
    second_name = ["静", "霞", "雪", "思", "平", "东", "志宏", 
        "峰", "磊", "雷", "文","明浩", "光", "超", "军", "达", 
        "伟", "华", "建国", "洋", "刚", "万里", "爱民", "牧", 
        "陆", "路", "昕", "鑫", "兵", "硕"]
    

    # 生成密码，hash加密
    password = generate_password_hash('123456')

    # 从词汇词典随机读取一个词汇的释义作为特长
    data = xlrd3.open_workbook('test/dicWords.xls')
    sheet = data.sheets()[0]
    key = sheet.col_values(0) #词汇
    val = sheet.col_values(1) #释义

    # 填零位数，最多可生成4位数用户
    zero = 4
    # 进入0~99个循环
    for iii in range(1,100):
        #随机生成姓名
        name = random.choice(first_name) + random.choice(second_name)
        # 生成目标照片文件名
        now = datetime.now() #当前时间
        strnow = now.strftime("%Y%m%d%H%M%s") + str(iii)
        imgname = strnow + '.png'
        # 随机生成1和2
        rand = random.randint(1, 2)
        if rand == 1: #男性
            gender = True
            copyfile('test/man.png', 'appdir/static/image/' + imgname)
        else: #女性
            gender = False
            copyfile('test/woman.png', 'appdir/static/image/' + imgname)
        
        # 随机生成1~4间的整数（含1和4）
        education = random.randint(1, 4)
        # 随机生成年龄
        if education == 1:
            age = random.randint(15, 30)
        elif education == 2:
            age = random.randint(18, 40)
        elif education == 3:
            age = random.randint(22, 50)
        else:
            age = random.randint(25, 60)
        
        # 生成出生日期
        y = datetime.now().year - age
        m = random.randint(1, 12) 
        d = random.randint(1, 28)
        birthday = parser.parse(f'{str(y)}-{str(m).zfill(2)}-{str(d).zfill(2)}')
        # 全国各省市名称
        pname = ['北京',
            '天津',
            '河北',
            '山西',
            '内蒙古',
            '辽宁',
            '吉林',
            '黑龙江',
            '上海',
            '江苏',
            '浙江',
            '安徽',
            '福建',
            '江西',
            '山东',
            '河南',
            '湖北',
            '湖南',
            '广东',
            '广西',
            '海南',
            '重庆',
            '四川',
            '贵州',
            '云南',
            '西藏',
            '陕西',
            '甘肃',
            '青海',
            '宁夏',
            '新疆',
            '台湾',
            '香港',
            '澳门']
        # 随机生成某个省名称
        province = pname[random.randint(0,33)]
        # 全疆各地州市名称
        rname = ['乌鲁木齐市',  
            '克拉玛依市', 
            '石河子市', 
            '吐鲁番市', 
            '哈密市', 
            '昌吉回族自治州', 
            '伊犁哈萨克自治州', 
            '塔城地区',
            '阿勒泰地区', 
            '博尔塔拉蒙古自治州', 
            '巴音郭楞蒙古自治州', 
            '阿克苏地区',
            '克孜勒苏柯尔克孜自治州',
            '喀什地区',
            '和田地区',
            '北屯市',
            '五家渠市',
            '铁门关市',
            '阿拉尔市',
            '图木舒克市',
            '昆玉市',
            '双河市',
            '可克达拉市'
            ]
        region = ''
        # 如果省市是新疆，则随机生成某个地州市
        if province == '新疆':
            region = rname[random.randint(0,20)]

        # 随机生成0~9组成的9位数字
        n9 = np.random.randint(0,9,size=9)
        # 生成电话号码
        ss =''.join([str(n) for n in n9])
        tel = f'13{ss}'
       
        # # 生成邮箱地址
        # if iii == 1: #管理员兼用户
        #     email = 'a@b.c'
        #     isadmin = True
        #     verify = True
        #     isviewer = False
        # elif iii == 2: #审核员
        #     email = 'v@b.c'
        #     isadmin = False
        #     isviewer = True
        #     verify = True
        # else: #用户
        #     email = f'{tel}@163.com'
        #     verify = None
        #     isadmin = False
        #     isviewer = False
        email = f'{tel}@163.com'
        verify = None
        isadmin = False
        isviewer = False

        # 爱好 
        # 随机产生包含1~4的4位数字
        n4 = np.random.randint(1,5,size=4)
        # 转换成字符串后删掉重复的数字
        hobby = ''
        for i in str(n4):
            if i not in hobby and i in '1234':
                hobby += i

        # 随机读取词典中的某词汇释义，赋给特长
        idx = random.randint(1,len(key))
        skill = f'{key[idx]}：{val[idx]}'
        
        
        # 用户注册信息写入User表
        user=User( 
            email = email, 
            isadmin = isadmin,
            isviewer = isviewer,
            verify = verify,
            password = password, 
            name = name,
            gender = gender, 
            birthday = birthday, 
            education = education, 
            province= province, 
            region = region, 
            image = imgname,
            hobby = hobby, 
            skill = skill)
        db.session.add(user)
        db.session.commit()

        # 一个用户5个资源
        rres = random.randint(1, 5)
        for ii in range(1,rres):
            rand = random.randint(1, 6)
            if rand == 1:
                restype = 'pptx'
            elif rand == 2:
                restype = 'docx'
            elif rand == 3:
                restype = 'pdf'
            elif rand == 4:
                restype = 'news'
            else:
                restype = 'mp4'

            if restype == 'news':
                f = open("test/4.txt",encoding = "utf-8")
                body = f.read()
                f.close()
            else:
                resname = f'/static/file/{strnow}.{restype}'
                copyfile(f'test/{rand}.{restype}', f'appdir{resname}')
            
            rand = random.randint(1, 3)
            if rand == 1:
                verify = True
            elif rand == 2:
                verify = False
            else:
                verify = None

            title = wisdom[iii]
            if restype == 'news':
                new = News(
                    email = email, 
                    title = title,
                    body = body,
                    time = now.date(),
                    verify = verify,
                    )
            else:
                # 资源信息写入Resource表
                new=Resource(
                    email = email, 
                    title = title,
                    resname = resname, 
                    restype = restype, 
                    verify = verify,
                    )

            db.session.add(new)
            db.session.commit()
    return '<div style="width: 300px; \
        margin:300px auto"><a href="/"> \
        <h1>数据生成完毕！</h1></a></div>'





